package it.yuzuojian.com.resolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import it.yuzuojian.com.pojo.MethodAndObject;
import it.yuzuojian.com.pojo.mvc.ModelAndView;
import it.yuzuojian.com.pojo.mvc.ModelMap;
import jdk.nashorn.internal.ir.IfNode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class InternalResourceViewResolver {


    private String PREFIX = "/";
    private String SUFFIX = ".jsp";

    private ObjectMapper objectMapper = new ObjectMapper();

    public void resolver(HttpServletRequest request, HttpServletResponse response,
                         ModelAndView modelAndView, MethodAndObject methodAndObject) throws ServletException, IOException {
        if (methodAndObject.isReturnJson()) {
            String s = objectMapper.writeValueAsString(modelAndView.getView());
            PrintWriter writer = response.getWriter();
            writer.println(s);
            return;
        }
        String path = null;
        String view = ((String) modelAndView.getView()).trim();
        ModelMap modelMap = modelAndView.getModel();
        if(modelMap!=null && modelMap.size()!=0){
            modelMap.forEach((key,value)->{
                request.setAttribute(key,value);
            });
        }
        if (view.contains(InternalResourceViewResolver.FORWARD_URL_PREFIX)) {
            String substring = view.substring(8).trim();
            path = this.getPREFIX()+substring
                    +this.getSUFFIX();
            request.getRequestDispatcher(path).forward(request, response);
        }else if (view.contains(InternalResourceViewResolver.REDIRECT_URL_PREFIX)){
            String substring = view.substring(9).trim();
            path = this.getPREFIX()+substring
                    +this.getSUFFIX();
            response.sendRedirect(path);
        }else {
            path = this.getPREFIX()+view
                    +this.getSUFFIX();
            request.getRequestDispatcher(path).forward(request, response);
        }
    }

    private boolean CompareModelMap(ModelMap model, ModelMap model1) {
        return model.equals(model1);
    }

    public static final String REDIRECT_URL_PREFIX = "redirect:";

    public static final String FORWARD_URL_PREFIX = "forward:";

    public String getPREFIX() {
        return PREFIX;
    }

    public void setPREFIX(String PREFIX) {
        this.PREFIX = PREFIX;
    }

    public String getSUFFIX() {
        return SUFFIX;
    }

    public void setSUFFIX(String SUFFIX) {
        this.SUFFIX = SUFFIX;
    }
}
